package org.yoao.crm.business.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.yoao.crm.bean.Customer;
import org.yoao.crm.bean.CustomerAttributes;
import org.yoao.crm.bean.User;
import org.yoao.crm.business.service.ICustomerService;
import org.yoao.crm.dao.CustomerAttributesDAO;
import org.yoao.crm.dao.CustomerDAO;
import org.yoao.crm.dao.RoleDAO;
import org.yoao.crm.dao.UserDAO;
import org.yoao.crm.struts.form.CustomerForm;
import org.yoao.crm.tools.CodeFactory;
import org.yoao.crm.tools.TimeTool;

public class CustomerServiceImpl implements ICustomerService {

	private CustomerDAO customerDAO = new CustomerDAO();
	private CustomerAttributesDAO customerAttributeDAO = new CustomerAttributesDAO();

	@Override
	public List view(int startRow, int endRow, Map map) throws Exception {
		return customerDAO.find(startRow, endRow, map);
	}

	@Override
	public CustomerForm getCustomer(String customerId) throws Exception {
		CustomerForm form = new CustomerForm();
		Customer customer = customerDAO.findShowById(customerId);
		if (customer != null)
			BeanUtils.copyProperties(form, customer);
		return form;
	}

	@Override
	public int getDataCount(Map map) throws Exception {
		return customerDAO.getDataCount(map);
	}

	@Override
	public CustomerForm add(CustomerForm form) throws Exception {
		return add(form, true);
	}

	private CustomerForm add(CustomerForm form, boolean flag) throws Exception {
		Customer customer = new Customer();
		form.setCustomerId(CodeFactory.getCostomerCodeBySQL());// 获取新客户码
		form.setCreateTime(TimeTool.getSystemTime());
		BeanUtils.copyProperties(customer, form);
		customer.setMobile(customer.getMobile().trim());

		Customer tmp = customerDAO.findCustomerById(customer.getCustomerId());
		if (tmp != null) {
			form.setInfo("客户码[" + tmp.getCustomerId() + "]已存在,重复!");
			return form;
		}
		tmp = null;

//		tmp = customerDAO.findByName(customer.getCustomerName());
//		if (tmp != null) {
//			form.setInfo("客户[" + tmp.getCustomerName() + "]已存在,重复!");
//			return form;
//		}
//		tmp = null;

		tmp = customerDAO.findCustomerByMobile(customer.getMobile());
		if (tmp != null) {
			form.setInfo("手机号[" + tmp.getMobile() + "]已存在,重复!");
			return form;
		}

		customer = customerDAO.insert(customer);
		if (customer != null) {
			String customerState = form.getState();
			BeanUtils.copyProperties(form, customer);
			if (flag) {
				CustomerAttributes customerAttribute = new CustomerAttributes();
				customerAttribute.setCustomerId(customer.getCustomerId());
				customerAttribute.setCustomerName(customer.getCustomerName());
				customerAttribute.setState(customerState);
				customerAttribute.setSignature(0);
				customerAttribute.setAmount(0);
				customerAttributeDAO.insert(customerAttribute);
			}
			form.setInfo("[SUCCESS]");
		} else
			form.setInfo("数据保存失败.");
		return form;
	}

	@Override
	public CustomerForm modify(CustomerForm form) throws Exception {
		Customer customer = new Customer();
		form.setCreateTime(TimeTool.getSystemTime());
		form.setModifyTime(TimeTool.getSystemTime());
		BeanUtils.copyProperties(customer, form);

//		Customer tmp = customerDAO.findByNameNoCustomerId(customer
//				.getCustomerName(), customer.getCustomerId());
//		if (tmp != null) {
//			form.setInfo("客户[" + tmp.getCustomerName() + "]已存在,重复!");
//			return form;
//		}
//		tmp = null;

		Customer tmp = customerDAO.findCustomerByMobileNoCustomerId(
				customer.getMobile(), customer.getCustomerId());
		if (tmp != null
				&& !tmp.getCustomerId().equals(customer.getCustomerId())) {
			form.setInfo("手机号[" + tmp.getMobile() + "]已存在,重复!");
			return form;
		}

		customer = customerDAO.modify(customer);
		if (customer != null) {
			BeanUtils.copyProperties(form, customer);
			form.setInfo("数据保存成功.");
		} else
			form.setInfo("数据保存失败.");
		return form;
	}

	@Override
	public void delete(String customerId) throws Exception {
		if (customerId.endsWith(","))
			customerId = customerId.substring(0, customerId.length() - 1);
		if (customerDAO.delete(customerId) > -1) {
			customerAttributeDAO.deleteByCustomerId(customerId);
		}
	}

	@Override
	public void signature(String value, String signTime, String customerType,
			String customerId) throws Exception {
		if (customerId.endsWith(","))
			customerId = customerId.substring(0, customerId.length() - 1);
		customerAttributeDAO.sign(null, value, signTime, customerType,
				customerId);
	}

	@Override
	public String allocation(String tableName, String id, String userSno,
			String assigner) throws Exception {
		StringBuffer relust = new StringBuffer();
		String customerType = "";
		String customerMemo = "";
		if ("signup".equalsIgnoreCase(tableName)) {
			customerType = "YCT-LYXLY";
			customerMemo = "老鹰训练营分配客户";
		} else if ("childs".equalsIgnoreCase(tableName)) {
			customerType = "YCT-XLY";
			customerMemo = "领袖少年特训营分配客户";
		} else if ("nac".equalsIgnoreCase(tableName)) {
			customerType = "YCT-YZWLSD";
			customerMemo = "赢在网络时代分配客户";
		} else if ("nacpx".equalsIgnoreCase(tableName)) {
			customerType = "YCT-YZWLSD";
			customerMemo = "游傲培训网分配客户";
		} else if ("mindPic".equalsIgnoreCase(tableName)) {
			customerType = "YCT-DLFCS";
			customerMemo = "思维导图分配客户";
		} else if ("swdt".equalsIgnoreCase(tableName)) {
			customerType = "YCT-DLFCS";
			customerMemo = "思维导图分配客户";
		} else if ("mmorder".equalsIgnoreCase(tableName)) {
			customerType = "YCT-WLZQJQ";
			customerMemo = "网络赚钱机器分配客户";
		} else if ("mmuser".equalsIgnoreCase(tableName)) {
			customerType = "YCT-WLZQJQ";
			customerMemo = "网络赚钱机器分配客户";
		} else if ("yyuser".equalsIgnoreCase(tableName)) {
			customerType = "YCT-YYCUST";
			customerMemo = "YY分配客户";
		}

		if (id != null && id.endsWith(","))
			id = id.substring(0, id.length() - 1);
		List lessonMenList = customerDAO.findLessonMen(tableName, id);
		if (lessonMenList != null && !lessonMenList.isEmpty()) {
			for (int i = 0; i < lessonMenList.size(); i++) {
				Map map = (Map) lessonMenList.get(i);
				CustomerForm form = new CustomerForm();
				form.setMemo(customerMemo);

				Iterator iter = map.keySet().iterator();
				CustomerAttributes customerAttributes = new CustomerAttributes();
				customerAttributes.setState(customerType);

				String pid = null;
				while (iter.hasNext()) {
					String key = iter.next().toString();
					if (key.equals("ID")) {
						pid = (String) map.get(key);
					}
					if (key.equals("CUSTNAME")) {
						form.setCustomerName((String) map.get(key));
					}
					if (key.equals("NAME")) {
						form.setCustomerName((String) map.get(key));
					}
					if (key.equals("SUBSCRIBER")) {
						form.setCustomerName((String) map.get(key));
					}
					if (key.equals("USERNAME")) {
						form.setCustomerName((String) map.get(key));
					}

					if (key.equals("MOBILE")) {
						form.setMobile((String) map.get(key));
					}
					if (key.equals("PHONE")) {
						form.setMobile((String) map.get(key));
					}
					if (key.equals("EMAIL")) {
						form.setEmail((String) map.get(key));
					}
					if (key.equals("QQ")) {
						form.setQQ((String) map.get(key));
					}
					if (key.equals("CITY")) {
						form.setCity((String) map.get(key));
					}
					if (key.equals("ADDRESS")) {
						form.setCity((String) map.get(key));
					}
					if (key.equals("CREATETIME")) {
						form.setCreateTime((String) map.get(key));
					}
					if (key.equals("BMTIME")) {
						form.setCreateTime((String) map.get(key));
					}
					if (key.equals("ISFLAG")) {
						String f = (String) map.get(key);
						if (f == null)
							f = "0";
						customerAttributes.setSignature(Integer.parseInt(f));
					}
					if (key.equals("MEMO")) {
						String m = (String) map.get(key);
						if (m != null && !m.trim().equals(""))
							form.setMemo(m);
					}
					if (key.equals("ORDERNUMBER")) {
						form.setMemo("网络赚钱机器客户:订单号[" + (String) map.get(key)
								+ "]");
						customerAttributes.setState("YCT-WLZQJQ");
					}
					if (key.equals("PRODUCTNAME")) {
						form.setMemo(form.getMemo() + " 产品["
								+ (String) map.get(key) + "]");
					}
					if (key.equals("EXPANDCODE")) {
						form.setMemo("网络赚钱机器注册客户");
						customerAttributes.setState("YCT-WLZQJQ");
					}
				}
				form.setUserSno(userSno);
				form.setIsNew(0);
				if (form.getCustomerName() == null
						|| form.getCustomerName().trim().equals("")) {
					continue;
				}
				if (form.getMobile() == null
						|| form.getMobile().trim().equals("")) {
					continue;
				}

				User user = new UserDAO().findBySno(userSno);
				form.setRoleId(user.getAccessSno());

				String address = form.getCity();
				int index = address.indexOf("省");
				if (index > 0) {
					form.setProvince(address.substring(0, index).trim());
					if (index < address.length() - 1)
						form.setCity(address.substring(index + 1,
								address.length()).trim());
				}
				form.setAssigner(assigner);

				form = add(form, false);
				if ("[SUCCESS]".equals(form.getInfo())) {
					customerAttributes.setCustomerId(form.getCustomerId());
					customerAttributeDAO.insert(customerAttributes);
					customerDAO.modifyLessonMen(tableName, pid, userSno);
				} else {
					relust.append(form.getInfo() + "\n");
					continue;
				}
			}
		}
		return relust.toString();
	}

	@Override
	public String distribution(String customerId, String userSno,
			String assigner, String owner, boolean isAdmin) throws Exception {
		if (customerId == null || customerId.trim().equals("")) {
			return "暂无需要非配的客户";
		}
		StringBuffer result = new StringBuffer();

		if (!isAdmin) {
			String[] custId = customerId.split(",");

			if (!customerId.startsWith(",")) {
				customerId = "," + customerId;
			}
			if (!customerId.endsWith(",")) {
				customerId = customerId + ",";
			}

			for (String cid : custId) {
				Customer temp = customerDAO.findCustomerById(cid);
				if (!temp.getUserSno().equals(owner)) {
					result.append(temp.getCustomerId() + ":"
							+ temp.getCustomerName() + " ");
					customerId = customerId.replaceAll("," + cid + ",", "");
				}
			}

			if (result.length() > 0) {
				result.insert(0, "您无权分配客户:");
			}
		}
		if (customerId.startsWith(",")) {
			customerId = customerId.substring(1);
		}
		if (customerId.endsWith(",")) {
			customerId = customerId.substring(0, customerId.length() - 1);
		}

		User user = new UserDAO().findBySno(userSno);
		if (customerDAO.modifyUerSno(customerId, userSno, user.getRole() + ";"
				+ new RoleDAO().findAllParentID(user.getRole()), assigner) > -1) {
			if (result.length() > 0) {
				return result.toString();
			} else {
				return "[SUCCESS]";
			}
		} else {
			return "分配失败.";
		}
	}

	@Override
	public String updateType(String customerId, String typeValue)
			throws Exception {
		if (customerId.endsWith(","))
			customerId = customerId.substring(0, customerId.length() - 1);
		if (customerDAO.modifyType(customerId, typeValue) > -1)
			return "[SUCCESS]";
		else
			return "分配失败.";
	}

	@Override
	public void modifyMemo(String id, String memo) {
		customerDAO.modifyMemo(id, memo);
	}
}